package com.huaxinkaiye.utils;

import android.content.Context;
import android.os.AsyncTask;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;

public abstract class PostTaskUtil extends AsyncTask<String, Void, String> {

    private Context context = null;

    public PostTaskUtil(Context context) {
        this.context = context;
    }

    public static String PHPSESSID = null;

    @Override
    protected String doInBackground(String... params) {
        String re = null;
        String url = new String(params[0]);
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 20000);
        HttpConnectionParams.setSoTimeout(httpParameters, 20000);
        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost(url);
        if(null != PHPSESSID){
        httpPost.setHeader("Cookie", "PHPSESSID=" + PHPSESSID);
        }
        int i;
        ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
        for (i = 1; i < params.length; i += 2)
            paramList.add(new BasicNameValuePair(params[i], params[i + 1]));

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if (httpResponse != null
                    && httpResponse.getStatusLine().getStatusCode() == 200)
                re = EntityUtils.toString(httpResponse.getEntity());
            //else
            //Toast.makeText(context, "网络异常！", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return re;
    }

    @Override
    public void onPostExecute(String re) {
        super.onPostExecute(re);
        callBack(re);
    }

    public abstract void callBack(String re);

}
